package com.ctw.tinyservices.id.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Optional;
import java.util.Properties;

/**
 * @author TongWei.Chen 2022/3/18 17:21
 *
 * Properties 工具类
 **/
public final class PropertiesUtils {

    private PropertiesUtils() {}

    public static Properties load(String location) {
        LogUtils.info(PropertiesUtils.class, "Loading properties file from path:[{}]", location);
        return load(PropertiesUtils.class.getClassLoader().getResourceAsStream(location));
    }

    public static Properties load(InputStream inputStream) {
        Properties props = new Properties();
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(inputStream, "UTF-8");
            props.load(in);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LogUtils.warn(PropertiesUtils.class, "error close inputstream", e);
                }
            }
        }
        return props;
    }

    public static String getPropertiesEnvPriority(Properties properties, String key) {
        return Optional.ofNullable(System.getenv(key)).orElse(properties.getProperty(key));
    }

}
